package com.jsb.laundry.controller;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.constant.LaundryModuleConstants;
import com.jsb.laundry.common.enums.ReturnStatusCode;
import com.jsb.laundry.common.response.WebResponse;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.baidu.CalLngLatUtil;
import com.jsb.laundry.common.utils.jhh.Withdrawal;
import com.jsb.laundry.dao.UserInfoCenterDao;
import com.jsb.laundry.model.dto.Property;
import com.jsb.laundry.model.dto.UserInfoCenterDto;
import com.jsb.laundry.model.entity.*;
import com.jsb.laundry.model.v1.MyInfo;
import com.jsb.laundry.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Api(tags = {"我的"})
@RestController
@RequestMapping("/userInfo")
public class UserInfoCenterController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserInfoCenterController.class);

    @Resource
    private UserInfoCenterDao userInfoCenterDao;

    @Resource
    private UserInfoService userInfoService;

    /**
     * 获取我的页面数据（userId）
     */
    @ApiOperation(value = "获取我的页面数据", notes = "我的页面数据", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户id", required = false, paramType = "body", dataType = "String")
    })
    @PostMapping("/center")
    public WebResponse<UserInfoCenterDto> getUserInfoCenter(@RequestBody UserDetail userDetail) {
        UserInfoCenterDto userInfoCenter = new UserInfoCenterDto();

        List<UserInfoCenterDto.GuessYouLike> guessYouLike = userInfoCenterDao.getLaundryActivityModel(LaundryModuleConstants.LAUNDRY_ACTIVITY_ID);

        List<Property> property = new ArrayList() {
            {
                add(new UserInfoCenterDto.AccountBalance());
                add(new UserInfoCenterDto.SchoolPackage());
                add(new UserInfoCenterDto.MonthCard());
                add(new UserInfoCenterDto.Coupon());
            }
        };
        userInfoCenter.setProperty(property).setGuessYouLike(guessYouLike);

        return WebResponse.successData(userInfoCenter);
    }

    /**
     * 修改个人详情
     *
     * @param userDetail
     * @return
     */
    @PostMapping("/detail/update")
    public WebResponse updateUserDetailById(@RequestBody UserDetail userDetail) {
        if (JSBUtil.isEmptyString(userDetail.getUserId())) {
            return WebResponse.failOfParameter();
        }
        int count = userInfoCenterDao.updateUserDetailById(userDetail);
        return WebResponse.successData(count);
    }

    /**
     * 查看收货地址(userId)
     */
    @ApiOperation(value = "查看收货地址", notes = "查看收货地址", httpMethod = "POST")
    @PostMapping("/findAddressByUserId")
    public WebResponse<List<UserAddress>> findAddressByUserId(@RequestBody UserAddress data) {
        LOGGER.info("用户：{},查看收货地址", data.getUserId());
        if (JSBUtil.isEmptyString(data.getUserId())) {
            return WebResponse.failOfParameter();
        }
        List<UserAddress> resultMsg = userInfoCenterDao.findUserAddressByUserId(data.getUserId());
        return WebResponse.successData(resultMsg);
    }


    /**
     * 添加收货地址
     *
     * @return
     */
    @ApiOperation(value = "添加收货地址", notes = "添加收货地址", httpMethod = "POST")
    @PostMapping("/saveAddress")
    public WebResponse saveAddress(@RequestBody UserAddress data) {
        LOGGER.info("确认订单页面保存地址" + data);
        //参数判空
        if (JSBUtil.isEmptyString(data.getUserId()) || JSBUtil.isEmptyString(data.getUserPhone()) || JSBUtil.isEmptyString(data.getUserAddress()) || JSBUtil.isEmptyString(data.getUserDetailAddress())) {
            return WebResponse.failOfParameter();
        }
        // TODO 用百度API获取用户经纬度
        String lngLat = CalLngLatUtil.getLngLat(data.getUserAddress() + data.getUserDetailAddress());
        data.setUserPointXY(lngLat);

        //新添加地址时,把该用户已存在的地址设置为非默认，当前新添加的地址为默认
        int var0 = userInfoCenterDao.updAddressNotDefault(data.getUserId());

        //TODO 地址不存在则添加，存在则修改
        if (JSBUtil.isEmptyString(data.getId())) {
            //新添加的地址为默认地址
            return WebResponse.successData(userInfoCenterDao.saveAddress(data));
        } else {
            return WebResponse.successData(userInfoCenterDao.updAddress(data));
        }
    }

    /**
     * 更新收货地址
     * 删除收货地址（delFlag=1）
     */
    @ApiOperation(value = "更新收货地址|删除收货地址（delFlag=1）", notes = "更新收货地址|删除收货地址", httpMethod = "POST")
    @PostMapping("/updAddress")
    public WebResponse updAddress(@RequestBody UserAddress data) {
        LOGGER.info("更新收货地址" + data);
        if (JSBUtil.isEmptyString(data.getUserId())) {
            return WebResponse.failOfParameter();
        }
        int ok = userInfoCenterDao.updAddress(data);
        return WebResponse.successData(ok);
    }

    /**
     * 设置默认地址(ID、userId)
     *
     * @param data
     * @return
     */
    @ApiOperation(value = "设置默认地址", notes = "设置默认地址", httpMethod = "POST")
    @PostMapping("/setDefaultAddress")
    public WebResponse setDefaultAddress(@RequestBody UserAddress data) {
        LOGGER.info("设置默认地址" + data);
        //参数判空
        if (JSBUtil.isEmptyString(data.getUserId()) || JSBUtil.isEmptyString(data.getId())) {
            return WebResponse.failOfParameter();
        }

        //新添加地址时,把该用户已存在的地址设置为非默认，当前新添加的地址为默认
        int var0 = userInfoCenterDao.updAddressNotDefault(data.getUserId());

        //TODO 设置为默认地址
        int var1 = userInfoCenterDao.updAddressDefault(data.getUserId(), data.getId());

        return WebResponse.successData(var1);
    }

    @PostMapping("/getOpenIdByUserId")
    public WebResponse getOpenIdByUserId(@RequestBody UserDetail userDetail) {
        if (JSBUtil.isEmptyString(userDetail.getUserId())) {
            return WebResponse.failOfParameter();
        }
        String openId = userInfoService.getOpenIdByUserId(userDetail.getUserId());
        return WebResponse.successData(openId);
    }

    /**
     * 朕的查询 (userId)
     *
     * @param data
     * @return
     */
    @PostMapping("/getList")
    public WebResponse findByMy(@RequestBody String data) {
        LOGGER.info("userId为:" + data);
        JSONObject jsonObject = JSONObject.parseObject(data);
        String userId = jsonObject.getString("userId");
        if (JSBUtil.isEmptyString(userId)) {
            return WebResponse.failOfParameter();
        }

        MyInfo byMy = userInfoCenterDao.findByMy(userId);
//        Date vip2Date = byMy.getVip2Date();
//        // 合作会员没有过期时Vip2才赋值
//        if (!JSBUtil.isEmptyObject(vip2Date) && vip2Date.after(new Date())) {
//            byMy.setVip2(JSBUtil.dateFormat(vip2Date));
//        }

        return WebResponse.successData(byMy);
    }


    /**
     * 获取用户账户余额页面(userId)
     */
    @PostMapping("/accountBalancePage")
    public WebResponse accountBalancePage(@RequestBody CouponUserBag couponRecord) {
        LOGGER.info("获取用户账户余额页面：{}", couponRecord);
        if (JSBUtil.isEmptyString(couponRecord.getUserId())) {
            HashMap map = new HashMap<>();
            map.put("userBalance", "0");
            map.put("userOtherBalance", "0");
            map.put("total", "0");
            return WebResponse.successData(map);
        }
        //业务处理
        HashMap returnMsg = userInfoCenterDao.accountBalancePage(couponRecord.getUserId());

        //返回数据
        return WebResponse.successData(returnMsg);
    }


    /**
     * 第三方实名认证接口
     *
     * @param idInfo
     * @return
     */
    @PostMapping("idInfos")
    public WebResponse idInfos(@RequestBody IdInfo idInfo) {
        if (JSBUtil.isEmptyString(idInfo.getIdNumber()) || JSBUtil.isEmptyString(idInfo.getIdName()) || JSBUtil.isEmptyString(idInfo.getReservedMobilePhone())
                || JSBUtil.isEmptyString(idInfo.getBankCard()) || JSBUtil.isEmptyString(idInfo.getFrontIdCard()) || JSBUtil.isEmptyString(idInfo.getReverseIdCard())) {
            return WebResponse.failOfParameter();
        }
        String s = Withdrawal.realName(idInfo.getIdNumber(), idInfo.getIdName(), idInfo.getReservedMobilePhone(), idInfo.getBankCard(), idInfo.getFrontIdCard(), idInfo.getReverseIdCard());
        return WebResponse.successData(s);
    }

    /**
     * 添加银行卡
     *
     * @param userBankCard
     * @return
     */
    @PostMapping("/addBankCard")
    public WebResponse addBankCard(@RequestBody UserBankCard userBankCard) {
        LOGGER.info("添加银行卡：{}", userBankCard);
        if (JSBUtil.isEmptyString(userBankCard.getUserId())) {
            return WebResponse.failOfParameter();
        }
        //检查用户是否绑定银行(一个用户只能有一张卡)
        int var0 = userInfoCenterDao.checkBankCard(userBankCard.getUserId());
        if (var0 == 0) { //不存在则添加
            //业务处理
            int var1 = userInfoCenterDao.addBankCard(userBankCard);
            return WebResponse.successData(var1);
        } else {
            return WebResponse.success(ReturnStatusCode.BINDING_BANK.getCode(), ReturnStatusCode.BINDING_BANK.getMsg());
        }
    }

    /**
     * 查询已添加的银行卡信息
     *
     * @param userBankCard
     * @return
     */
    @PostMapping("/findBankInfoByUserId")
    public WebResponse findBankInfoByUserId(@RequestBody UserBankCard userBankCard) {
        LOGGER.info("查询已添加的银行卡信息：{}", userBankCard);
        if (JSBUtil.isEmptyString(userBankCard.getUserId())) {
            return WebResponse.failOfParameter();
        }
        //业务处理
        List<UserBankCard> var0 = userInfoCenterDao.findBankInfoByUserId(userBankCard.getUserId());
        //返回数据
        return WebResponse.successData(var0);
    }

    /**
     * 微信小程序用户体现（userId、money、id）
     *
     * @param riderEmbodiment
     * @return
     */
    @PostMapping("userWithdrawal")
    public WebResponse userWithdrawal(@RequestBody RiderEmbodiment riderEmbodiment) {
        if (JSBUtil.isEmptyString(riderEmbodiment.getUserId()) || JSBUtil.isEmptyString(riderEmbodiment.getMoney()) || JSBUtil.isEmptyString(riderEmbodiment.getId())) {
            return WebResponse.failOfParameter();
        }
        //判断用户余额是否能提现
//        Map<String,String> money = laundryRiderInfoService.findByMoney(riderEmbodiment.getUserId());
//        String userBalance = money.get("userBalance");
//        double v = Double.parseDouble(userBalance);
//        double v1 = Double.parseDouble(riderEmbodiment.getMoney());
//        if (v1<0||v1>v){
//            return WebResponse.successData(null);
//        }
        HashMap<String, String> var0 = userInfoCenterDao.userBankInfo(riderEmbodiment.getUserId(), riderEmbodiment.getId());
        if (var0 == null) {
            return WebResponse.successData(null);
        }

        String withdrawal = Withdrawal.withdrawal(var0.get("bank_card_id"),
                var0.get("bank_name"),
                var0.get("real_name"),
                var0.get("user_phone"),
                Double.parseDouble(riderEmbodiment.getMoney()),
                var0.get("user_id_number")
        );
        return WebResponse.successData(withdrawal);
    }


    /**
     * 提现时，添加提现记录(userId、withdrawalMoney、withdrawalType[提现类型：0：立即提现，1：其他收益提现])
     */
    @PostMapping("/addUserStreamRecord")
    public WebResponse addUserStreamRecord(@RequestBody CouponUserBag couponRecord) {
        LOGGER.info("提现时，添加提现记录：{}", couponRecord);
        if (JSBUtil.isEmptyString(couponRecord.getUserId()) || JSBUtil.isEmptyString(couponRecord.getWithdrawalType())
                || JSBUtil.isEmptyString(couponRecord.getWithdrawalMoney()) || Double.parseDouble(couponRecord.getWithdrawalMoney()) <= 0) {
            return WebResponse.failOfParameter();
        }
        //查看用户的账户余额
        HashMap accountInfo = userInfoCenterDao.accountBalancePage(couponRecord.getUserId());
        if (JSBUtil.isEmptyObject(accountInfo)) {
            return WebResponse.success(ReturnStatusCode.WX_USER_ACCOUNT_ABNORMAL.getCode(), ReturnStatusCode.WX_USER_ACCOUNT_ABNORMAL.getMsg());
        }
        Double userBalance = Double.parseDouble(accountInfo.get("userBalance").toString());//可以立即提现的金额
        Double userOtherBalance = Double.parseDouble(accountInfo.get("userOtherBalance").toString());//其他收益的金额

        /**
         *  提现类型：0：立即提现 余额不足
         */
        if ("0".equals(couponRecord.getWithdrawalType()) && Double.parseDouble(couponRecord.getWithdrawalMoney()) > userBalance) {
            return WebResponse.success(ReturnStatusCode.WX_USER_ACCOUNT_BALANCE_DEFICIENCY.getCode(), ReturnStatusCode.WX_USER_ACCOUNT_BALANCE_DEFICIENCY.getMsg());
        }
        /**
         * 提现类型：1：其他收益提现 余额不足、提现时间未到
         */
        Date withdrawAbleTime = userInfoCenterDao.findWithdrawalTime(couponRecord.getUserId());
        if ("1".equals(couponRecord.getWithdrawalType()) && Double.parseDouble(couponRecord.getWithdrawalMoney()) > userOtherBalance) { //验证提现时间
            if (JSBUtil.isEmptyObject(withdrawAbleTime) || withdrawAbleTime.getTime() > System.currentTimeMillis()) {
                return WebResponse.success(ReturnStatusCode.WX_USER_ACCOUNT_BALANCE_TIME_LIMIT.getCode(), ReturnStatusCode.WX_USER_ACCOUNT_BALANCE_TIME_LIMIT.getMsg());
            }
            return WebResponse.success(ReturnStatusCode.WX_USER_ACCOUNT_BALANCE_DEFICIENCY.getCode(), ReturnStatusCode.WX_USER_ACCOUNT_BALANCE_DEFICIENCY.getMsg());
        }

        //TODO 提现记录流水id user_stream_record
        String streamId = "withdraw-" + JSBUtil.generateUUID();
        couponRecord.setStreamId(streamId);
        couponRecord.setWithdrawalMoney(String.valueOf(Double.parseDouble(couponRecord.getWithdrawalMoney()) * 100));

        //添加记录
        int var1 = userInfoCenterDao.addUserStreamRecord(couponRecord);
        if (var1 != 0) { //扣除本次提现的金额
            int var0 = userInfoCenterDao.outAccountMoney(couponRecord);//提现类型：0：立即提现,1：其他收益提现
        }
        //返回数据
        return WebResponse.successData(var1);
    }


}
